# 设置三方库安装路径
set(INSTALL_PREFIX ${CMAKE_BINARY_DIR}/third_party/cjson)

# 利用本地缓存
# 查找头文件路径是否存在
find_path(cjson_INCLUDE_DIR
    NAMES cjson/cJSON.h
    PATHS ${INSTALL_PREFIX}/include/
    NO_DEFAULT_PATH
)
find_library(cjson_LIBRARY
    NAMES cjson
    PATHS ${INSTALL_PREFIX}/lib64
    NO_DEFAULT_PATH
)
if(NOT ${cjson_INCLUDE_DIR} STREQUAL cjson_INCLUDE_DIR-NOTFOUND AND NOT ${cjson_LIBRARY} STREQUAL cjson_LIBRARY-NOTFOUND)
    set(cjson_FOUND TRUE)
    return ()
endif ()

# 采用外部下载
if(NOT TARGET cjson)
    include(ExternalProject)
    ExternalProject_Add(
        cjson
        GIT_REPOSITORY https://github.com/DaveGamble/cJSON.git
        GIT_TAG v1.7.17
        CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}
        DOWNLOAD_NO_PROGRESS FALSE
    )
endif ()

find_path(cjson_INCLUDE_DIR
    NAMES cjson/cJSON.h
    PATHS ${INSTALL_PREFIX}/include/
    NO_DEFAULT_PATH
)
find_library(cjson_LIBRARY
    NAMES cjson
    PATHS ${INSTALL_PREFIX}/lib64
    NO_DEFAULT_PATH
)
if (NOT ${cjson_INCLUDE_DIR} STREQUAL cjson_INCLUDE_DIR-NOTFOUND AND NOT ${cjson_LIBRARY} STREQUAL cjson_LIBRARY-NOTFOUND)
    # 设置三方库安装成功标识符
    set(cjson_FOUND TRUE)
    # 导入编译结果至共享库
    add_library(cjson SHEAD IMPORTED)
    # 设置cjson的属性值, 供外部调用
    set_target_properties(cjson PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES ${cjson_INCLUDE_DIR}
        IMPORTED_LOCATION ${cjson_LIBRARY}
    )
endif ()

